package com.lqg.bookLibrary.common.securityImpl;

import cn.hutool.core.util.StrUtil;
import com.lqg.bookLibrary.common.util.JwtUtils;
import com.lqg.bookLibrary.pojo.Users;
import com.lqg.bookLibrary.service.IUsersService;
import com.lqg.bookLibrary.service.impl.LoginUserServiceImpl;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.apache.catalina.security.SecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.log.LogMessage;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 86183
 */
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    private LoginUserServiceImpl userDetailService;

    @Autowired
    private IUsersService userService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        String jwt = request.getHeader(jwtUtils.getHeader());
        //System.out.println(jwt);
        if (StrUtil.isBlankOrUndefined(jwt)) {
            chain.doFilter(request, response);
            return;
        }



        Claims claim = jwtUtils.getClaimByToken(jwt);
        if (claim == null) {
            //throw new JwtException("token 异常");
            //resolver.resolveException(request, response, null,
            //        new JwtException("token 异常"));
            //return;
            chain.doFilter(request, response);
        }
        if (jwtUtils.isTokenExpired(claim)) {
            //throw new JwtException("token已过期");
            //resolver.resolveException(request, response, null,
            //        new JwtException("token已过期"));
            //return;
            Long userId = Long.parseLong(claim.getSubject());
            String new_jwt = jwtUtils.generateToken(userId.toString());
            response.setHeader(jwtUtils.getHeader(), new_jwt);
            //chain.doFilter(request, response);
        }

        Long userId =  Long.parseLong(claim.getSubject());
        // 获取用户的权限等信息

        Users user = userService.lambdaQuery().eq(Users::getUserId,userId).one();
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

         // 权限信息
        for(String s : user.getRole().split(" ")){
            s="ROLE_"+s;
            grantedAuthorities.add(new SimpleGrantedAuthority(s));
        }

        UsernamePasswordAuthenticationToken token
                = new UsernamePasswordAuthenticationToken(user.getUsername(),
                null, grantedAuthorities);

        SecurityContextHolder.getContext().setAuthentication(token);

        chain.doFilter(request, response);
    }
}
